package cn.org.atool.generator.database.config.impl;

import cn.org.atool.generator.database.model.FieldType;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeName;
import lombok.Data;
import lombok.experimental.Accessors;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;

import java.util.HashMap;
import java.util.Map;

/**
 * 字段定义
 *
 * @author wudarui
 */
@SuppressWarnings({"rawtypes", "unused"})
@Data
@Accessors(chain = true)
public class ColumnConfig {
    /**
     * 数据库字段名称
     */
    private String column;

    /**
     * Entity属性名称
     */
    private String field;

    /**
     * insert的默认值
     */
    private String insert;

    /**
     * update的默认值
     */
    private String update;

    /**
     * 是否大字段
     */
    private boolean isLarge = false;

    /**
     * 显式指定字段对应的java类型
     */
    private TypeName javaType;

    /**
     * 显式指定jdbc type
     */
    private JdbcType jdbcType;

    /**
     * type handler
     */
    private Class<? extends TypeHandler> typeHandler;

    /**
     * 指定字段类型
     */
    private FieldType category;

    public void setJavaType(Class klass) {
        this.javaType = ClassName.get(klass);
    }

    public void setJavaType(Class klass, Class... argTypes) {
        this.javaType = ParameterizedTypeName.get(klass, argTypes);
    }

    public static final Map<String, ColumnConfig> configs = new HashMap<>();

    public static ColumnConfig set(String table, String column, String field) {
        return set(table, column).setField(field);
    }

    public static ColumnConfig set(String table, String column) {
        ColumnConfig config = new ColumnConfig().setColumn(column);
        configs.put(table + "#" + column, config);
        return config;
    }

    public static ColumnConfig get(String tableName, String columnName) {
        if (configs.containsKey(tableName + "#" + columnName)) {
            return configs.get(tableName + "#" + columnName);
        } else {
            return configs.get("*#" + columnName);
        }
    }
}
